package com.jp.knowledge.logic;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;

import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.util.PushUtil;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.util.SharedUtil;
import com.jp.knowledge.view.JpApplicationWebView;

import java.io.File;
import java.util.List;

/**
 * Created by jiayen on 16/11/14.
 *
 * 获取用户信息类
 */

public class PersonLogic implements ResultSubscriber.OnResultListener {
    private Context mContext;

    private JpApplication application;
    private UserDataCallBack callBack;

    private LocalBroadcastManager localBroadcastManager;

    private String cachePath;
    private FileCacheManager cacheManager;

    public PersonLogic(Context context){
       this(context,null);
    }
    public PersonLogic(Context context,UserDataCallBack userDataCallBack){
        this.callBack = userDataCallBack;
        application = (JpApplication) ((Activity)context).getApplication();
        this.mContext=context;
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        initCache(context);
    }

    public void setCallBack(UserDataCallBack callBack) {
        this.callBack = callBack;
    }

    public void getUserData(){
        JsonObject param = new JsonObject();
        HttpHelper.getInstance(mContext).userDetail(param,1,this);
    }
    public void getUserData(String code){
        JsonObject param = new JsonObject();
        param.addProperty("code",code);
        HttpHelper.getInstance(mContext).userDetail(param,1,this);
    }


    private void initCache(Context context){
        cachePath = context.getCacheDir().getPath() + "/userData.dat";
        cacheManager = new FileCacheManager();
    }
    @Override
    public void onStart(int requestType) {

    }

    @Override
    public void onCompleted(int requestType) {

    }

    @Override
    public void onError(int requestType) {

    }

    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            ToasUtil.toast(mContext,data.getMessage());
            onError(requestType);
        } else if(requestType == 1){
            UserData userData = data.getEntity(UserData.class);
            application.setUserData(userData);
            if(TextUtils.isEmpty(userData.getUuid())){
                userData.setUuid(HttpHelper.uuid);
            }
            if(TextUtils.isEmpty(userData.getToken())){
                userData.setToken(HttpHelper.token);
            }

//            JpApplicationWebView.getInstance(mContext).setUserDataToH5(userData);

            if(userData!=null&&userData.getIsLogin()==1){//处于登录状态则发送一则广播去通知需要的地方修改
                String secuCode  = userData.getSecuCode();
                if(!TextUtils.isEmpty(secuCode)) {
                    HttpHelper.token = userData.getToken();
                    HttpHelper.uuid = secuCode;
                    SharedUtil.getInstance(mContext).saveTokenAndUUId(HttpHelper.token, HttpHelper.uuid);
//                    ToasUtil.toast(mContext, "登录成功");
                }
//                saveUserDataToCache(userData);
                //拼接公司数据
//                userData.setOrganization(getOrganization(userData));
                Intent intent = new Intent();
                intent.setAction(LocalBroadCast.GET_LOGIN_INFO);
                localBroadcastManager.sendBroadcast(intent);
//                application.closeLoginActivity();
            }
            PushUtil.addAlias(userData);//添加推送别名
            if(callBack!=null)
                callBack.done(userData);
        }
    }

    /**
     * 拼接公司数据
     * @param userData
     * @return
     */
    private String getOrganization(UserData userData) {
       List<OrganizaModel>  companys = userData.getCompanyList();

        StringBuilder sb   = new StringBuilder();
        for (OrganizaModel company:companys) {
                sb.append(",").append(company.getCompanyFullName());
        }
        return sb.substring(1);
    }

    /**
     * 回调
     */
    public interface   UserDataCallBack{
        void done(UserData userData);
    }

    /***
     * 删除用户缓存
     */
    public void deleteUserData(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                File file = new File(cachePath);
                if(file.exists()){
                    file.delete();
                }
            }
        }).start();
    }

    /**
     * 保存用户信息如缓存
     * @param userData
     */
    private void saveUserDataToCache(final UserData userData){
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(userData, cachePath);
            }
        }).start();
    }
}
